package com.zjun.demo.experimentaldemo.udp.server

import com.zjun.demo.experimentaldemo.udp.call.ICallBackMsg
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler
import io.netty.channel.socket.DatagramPacket
import io.netty.util.CharsetUtil
import io.netty.util.internal.ThreadLocalRandom

/**
 * UDP Server Handler Class
 *
 */
class UdpServerHandler(val iCallBackMsg: ICallBackMsg?) : SimpleChannelInboundHandler<DatagramPacket>() {

    /**
     * 随机返回谚语
     */
    private fun nextProverb(): String {
        val nextInt = ThreadLocalRandom.current().nextInt(proverbs.size)
        return proverbs[nextInt]
    }

    /**
     * 随机返回成语
     */
    private fun nextIdiom(): String {
        val nextInt = ThreadLocalRandom.current().nextInt(idioms.size)
        return idioms[nextInt]
    }

    @Throws(Exception::class)
    override fun channelRead0(ctx: ChannelHandlerContext, msg: DatagramPacket) {
        val message = msg.content().toString(CharsetUtil.UTF_8)
        iCallBackMsg?.callMsg(message)
        println("服务端接收到的消息：$message")
        val sendMessage: String = when (message) {
            "谚语" -> {
                nextProverb()
            }
            "成语" -> {
                nextIdiom()
            }
            else -> {
                "请发送：“谚语”或者“成语”"
            }
        }
        ctx.writeAndFlush(DatagramPacket(Unpooled.copiedBuffer(sendMessage, CharsetUtil.UTF_8), msg.sender()))
    }

    @Throws(Exception::class)
    override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) {
        cause.printStackTrace()
        ctx.close()
    }

    companion object {

        private val proverbs = arrayOf(
            "只要功夫深，铁棒磨成针。", "旧时王谢堂前燕，飞入寻常百姓家。", "洛阳亲友如相问，一片冰心在玉壶。",
            "一寸光阴一寸金，寸金难买寸光阴。", "老骥伏枥，志在千里。烈士暮年，壮心不已!"
        )

        private val idioms = arrayOf("马到成功", "狐假虎威", "虎头虎脑", "生龙活虎", "如雷贯耳", "持之以恒")

    }
}
